import {
  queryPageDataReq,
  addItemReq,
  updateItemReq,
  deleteItemReq,
  toggleStateReq,
  queryMenuPageDataReq,
  queryAuthUserPageDataReq,
  deleteAuthUserItemReq,
  queryRoleMenuPageDataReq,
} from "./services";
import { namespace } from "./configFile";
import { message } from "antd";

export default {
  namespace,
  state: {
    init: false,
    data: {},
    menu: [],
  },
  effects: {
    *pageInit({ params }, { call, put }) {
      const res = yield call(queryMenuPageDataReq, params);
      console.log(res);
      yield put({
        type: "save",
        payload: {
          menu: res.menus,
        },
      });
    },
    *queryTable({ params }, { call, put }) {
      const res = yield call(queryPageDataReq, params);
      yield put({
        type: "save",
        payload: {
          ...params,
          ...res.rows,
        },
      });
      return {
        success: true,
        data: res.records,
        total: res.total,
      };
    },

    *queryRoleMenu({ params, callback }, { call, put }) {
      const res = yield call(queryRoleMenuPageDataReq, params);
      if (res) {
        callback && callback(res);
      } else {
        message.error(res.msg);
      }
    },

    *queryAuthUser({ params }, { call, put }) {
      if (!params.roleId) {
        return;
      }
      const res = yield call(queryAuthUserPageDataReq, params);
      yield put({
        type: "save",
        payload: {
          ...params,
          ...res.rows,
        },
      });
      return {
        success: true,
        data: res.records,
        total: res.total,
      };
    },

    *submitItem({ params, callback }, { call }) {
      let res = null;
      if (params.roleId) {
        res = yield call(updateItemReq, params);
      } else {
        res = yield call(addItemReq, params);
      }
      if (res?.code === 200) {
        message.success(res.msg);
        callback && callback();
      } else {
        message.error(res.msg);
      }
    },

    *deleteItem({ params, callback }, { call }) {
      let res = yield call(deleteItemReq, params);
      if (res?.code === 200) {
        message.success(res.msg);
        callback && callback();
      } else {
        message.error(res.msg);
      }
    },

    *deleteAuthUser({ params, callback }, { call }) {
      let res = yield call(deleteAuthUserItemReq, params);
      if (res?.code === 200) {
        message.success(res.msg);
        callback && callback();
      } else {
        message.error(res.msg);
      }
    },

    *queryItemInfo({ params, callback }, { call }) {},

    *toggleState({ params, callback }, { call }) {
      let res = yield call(toggleStateReq, params);
      if (res?.code === 200) {
        message.success(res.msg);
        callback && callback();
      } else {
        message.error(res.msg);
      }
    },
  },
  reducers: {
    save(state: any, { payload }: any) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
